import store from '@/store/index.js'

const getEnvUrl = async (url) => {
	let userTmp1 = uni.getStorageSync('user')
	if (!userTmp1) {
		uni.reLaunch({
		  url: '/pages/profile/login'
		})
		return
	}
	let user = JSON.parse(userTmp1)
	// console.log("请求地址ip"+user.serverip)
	// console.log("请求地址port"+user.serverport)
	if (!user.serverip || !user.serverport) {
	  uni.reLaunch({
	    url: '/pages/profile/login'
	  })
	  return
	}
	let username= user.username
	let password= user.password
	let serverip= user.serverip
	let serverport= user.serverport
	if (!serverport || !serverip) {
		return
	}
	if (!url.startsWith("http")) {
		let serverUrl = `${serverip}:${serverport}`
		if (!serverUrl.startsWith('http')) {
			serverUrl = `http://${serverUrl}`
		}
		url = serverUrl + url
	}
	let qureyAppend =
		`X-Emby-Client-Version=${user.deviceVersion}&X-Emby-Client=Emby+app&X-Emby-Device-Name=${user.deviceName}&X-Emby-Device-Id=${user.deviceId}&X-Emby-Language=zh-cn`
	let token= uni.getStorageSync('token')
	if (token) {
		qureyAppend += `&X-Emby-Token=${token}`
	}
	if (!url.includes("?")) {
		// 不包含?,就加上?
		url += `?${qureyAppend}`
	} else if (url.includes("&")) {
		// 不包含&,就加上&
		url += `&${qureyAppend}`
	} else {
		url += qureyAppend
	}
	return url
}

const post = async (url, postData, storeObj = null) => {
	url = await getEnvUrl(url)
	const data = Object.assign(postData ? postData : {}, {
		// timestamp: new Date().getTime()
	})

	let storeTemp = storeObj || store
	// console.log("当前请求地址"+url+";参数"+JSON.stringify(data))
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			method: 'POST',
			data: data,
			header: {
				clientType: 'h5',
				Authorization: 'Bearer ' + storeTemp.state.token
			},
			success(result) {
				if (result.statusCode == 401) {
					if (result.data) {
						uni.showToast({
							title: result.data,
							icon: 'error'
						})
					}
					storeTemp.commit('logout')
					if(!url.includes("Users/authenticatebyname")){
						uni.reLaunch({
							url: '/pages/profile/login'
						})
					}
					reject(result)
				} else if (result.data && result.statusCode != 200) {
					if (result.data) {
						uni.showToast({
							title: result.data,
							icon: 'error'
						})
					}
					reject(result)
				} else {
					resolve(result.data)
				}
			},
			fail(event) {
				reject(event)
			}
		})
	})
}

const get = async (url, getData, storeObj = null) => {
	url = await getEnvUrl(url)
	const data = Object.assign(getData ? getData : {}, {
		// timestamp: new Date().getTime()
	})
	let storeTemp = storeObj || store
    // console.log("当前请求地址"+url+";参数"+JSON.stringify(data))
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			method: 'GET',
			data: data,
			header: {
				clientType: 'h5',
				Authorization: 'Bearer ' + storeTemp.state.token
			},
			success(result) {
				if (result.statusCode == 401) {
					if (result.data) {
						uni.showToast({
							title: result.data,
							icon: 'error'
						})
					}
					storeTemp.commit('logout')
					if(!url.includes("Users/authenticatebyname")){
						uni.reLaunch({
							url: '/pages/profile/login'
						})
					}
					reject(result)
				} else {
					resolve(result.data)
				}
			},
			fail(event) {
				reject(event)
			}
		})
	})
}
const upload = async (filePath) => {
	url = getEnvUrl()
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: url + '/public/upload',
			filePath: filePath,
			name: 'file',
			success: (uploadFileRes) => {
				if (uploadFileRes.statusCode == 200) {
					const res = JSON.parse(uploadFileRes.data)
					resolve(res.data)
				} else {
					reject(uploadFileRes)
				}
			},
			fail(e) {
				reject(e)
				console.log('fail', e)
			}
		})
	})
}

export default {
	post,
	get,
	upload
}